package cn.ibizlab.util.service;

import cn.ibizlab.util.domain.FileItem;
import cn.ibizlab.util.errors.InternalServerErrorException;
import cn.ibizlab.util.security.AuthenticationUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

@Primary
@Slf4j
@Service
public class SimpleFileService implements FileService {

    @Value("${ibiz.filePath:/app/file/}")
    private String fileRoot;

    @Override
    public FileItem saveFile(MultipartFile multipartFile) {
        FileItem item = null;
        // 获取文件名
        String name = multipartFile.getOriginalFilename();
        try {
            String id = DigestUtils.md5DigestAsHex(multipartFile.getInputStream());
            Path path = Paths.get(this.fileRoot,"ibizutil",id,name);
            File parent = path.getParent().toFile();
            if(!parent.exists()) {
                parent.mkdirs();
            }
            FileCopyUtils.copy(multipartFile.getInputStream(), Files.newOutputStream(path));
            item = new FileItem().setId(id).setName(name).setTime(new Date()).setAuthor(AuthenticationUser.getAuthenticationUser().getDisplayName());
        } catch (IOException e) {
            throw new InternalServerErrorException("文件上传失败，"+e);
        }
        return item;
    }

    @Override
    public File getFile(String fileid) {
        File parent = Paths.get(this.fileRoot,"ibizutil",fileid).toFile();
        if (parent.exists() && parent.isDirectory() && parent.listFiles().length > 0) {
            return parent.listFiles()[0];
        }
        throw new InternalServerErrorException("文件未找到");
    }

}